# Copyright 2008 Tony Gentilcore
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from useragents import UserAgent

# TODO: Associate benchmarks w/ suites more strongly.

class Benchmark(db.Model):
  id = db.IntegerProperty(required=True)
  owner = db.UserProperty()
  name = db.StringProperty(required=True)
  body = db.TextProperty(required=True)


class Suite(db.Model):
  owner = db.UserProperty()
  name = db.StringProperty(required=True)
  iterations = db.IntegerProperty()
  params = db.TextProperty()
  benchmark_ids = db.ListProperty(db.Key)


class Run(db.Model):
  benchmark = db.ReferenceProperty(Benchmark)
  platform = db.StringProperty()
  browser = db.StringProperty()
  version = db.StringProperty()
  runs = db.IntegerProperty(required=True)
  exectime_ms = db.FloatProperty(required=True)


def GetBenchmark(id):
  return Benchmark.gql('WHERE id = :id', id=long(id)).get()


def CreateOrUpdateBenchmark(id, owner, name, body):
  benchmark = GetBenchmark(id)
  if not benchmark or owner == benchmark.owner:
    if not benchmark:
      benchmark = Benchmark(id=long(id), owner=owner, name=name, body=body)
    elif owner == benchmark.owner:
      benchmark.name = name
      benchmark.body = body.replace('\n', '\\n').replace('\r', '')
    benchmark.put()
  return benchmark


def CreateOrUpdateRun(benchmark, useragent, runs, time):
  # Lookup previous runs.
  run = Run.gql('WHERE benchmark = :benchmark AND '
                'platform = :platform AND '
                'browser = :browser AND '
                'version = :version', benchmark=benchmark,
                platform=useragent.platform,
                browser=useragent.browser,
                version=useragent.version).get()

  # If there were no previous runs, create a new one.
  if not run:
    run = Run(benchmark=benchmark.key(),
              platform=useragent.platform,
              browser=useragent.browser,
              version=useragent.version,
              runs=0,
              exectime_ms=0.0)

  # Add these runs and save it.
  run.runs += int(runs)
  run.exectime_ms += float(time)
  run.put()


class SaveRuns(webapp.RequestHandler):
  def post(self):
    self.response.headers['Content-Type'] = 'text/plain'
    user = users.get_current_user()
    useragent = UserAgent(self.request.headers['User-agent'])

    # Lookup or create this benchmark.
    runs = []
    bm_runs = self.request.get('bm_runs', allow_multiple=True)
    bm_times = self.request.get('bm_times', allow_multiple=True)
    i = 0
    for id in self.request.get('bm_ids', allow_multiple=True):
      benchmark = GetBenchmark(id)
      if benchmark:
        CreateOrUpdateRun(benchmark, useragent, bm_runs[i], bm_times[i])
        if i == 0:
          # The first time determine the list of browsers we will show.
          # TODO(tonyg): It would be nice to pick distinct browsers instead of
          # just the top 3.
          runs += [Run.gql('WHERE benchmark = :benchmark '
                           'ORDER BY runs DESC LIMIT 3',
                           benchmark=benchmark.key())]
        else:
          # Subsequent times, get that same list
          curr_runs = []
          for run in runs[0]:
            curr_runs += Run.gql('WHERE benchmark = :benchmark AND '
                                 'platform = :platform AND '
                                 'browser = :browser AND '
                                 'version = :version ORDER BY runs DESC '
                                 'LIMIT 1',
                                 benchmark=benchmark,
                                 platform=run.platform,
                                 browser=run.browser,
                                 version=run.version)
          runs += [curr_runs]
            
      i += 1

    # Return the average times for the top 3 user agents.
    response = []
    for run in runs:
      responses = []
      for r in run:
        responses += ["'%s %s %s':%f" % (r.browser, r.version, r.platform,
                                         r.exectime_ms / r.runs)]
      response += ['{%s}' % ','.join(responses)]
    self.response.out.write('[%s]' % ','.join(response))


class SaveBench(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    CreateOrUpdateBenchmark(self.request.get('id'),
                            user,
                            self.request.get('name'),
                            self.request.get('body'))


class SaveSuite(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if not user:
      # TODO handle this somehow
      return

    benchmark_ids = []
    benchmark_names = self.request.get('bm_name', allow_multiple=True)
    benchmark_bodies = self.request.get('bm_body', allow_multiple=True)
    i = 0
    for id in self.request.get('bm_id', allow_multiple=True):
      if id:
        benchmark = CreateOrUpdateBenchmark(id, user, benchmark_names[i],
                                            benchmark_bodies[i])
        benchmark_ids += [benchmark.key()]
      i += 1

    # First try to get the suite by id.
    suite = None
    id = self.request.get('id')
    if id:
      suite = Suite.get(id)
      if suite and suite.owner != user:
        # Only the owner can save this suite.
        return

    # If there was no id, try to get it by name.
    name = self.request.get('name')
    if not suite:
      suite = Suite.gql('WHERE owner = :owner AND name = :name',
                        owner=user, name=name).get()

    # If there is no existing suite, create a new one.
    if not suite:
      suite = Suite(owner=user, name=name)

    # Modify the suite and add/update it.
    suite.name = name
    suite.iterations = long(self.request.get('iters'))
    suite.params = self.request.get('params')
    suite.benchmark_ids = benchmark_ids
    suite.put()

    # Return the suite's id.
    self.response.out.write(suite.key())


class GetSuite(webapp.RequestHandler):
  def post(self):
    suite_id = self.request.get('id')
    if not suite_id:
      return
    suite = Suite.get(suite_id)
    if not suite:
      # How to handle this?
      return

    benchmarks = []
    for benchmark_id in suite.benchmark_ids:
      benchmark = Benchmark.get(benchmark_id)
      if benchmark:
        benchmarks += ["%s" % benchmark.body]
    
    self.response.out.write("{name:'%s',iterations:%d,params:'%s',"
                            "benchmarks:[%s]}" %
                            (suite.name, suite.iterations, suite.params,
                             ','.join(benchmarks)))


class ListSuites(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    useragent = UserAgent(self.request.headers['User-agent'])

    # List all suites that belong to this user.
    suites = Suite.gql('WHERE owner = :owner ORDER BY name', owner=user)
    responses = ["useragent:'%s %s %s'" % (useragent.browser,
                                           useragent.version,
                                           useragent.platform)]
    for suite in suites:
      # TODO handle escaping here and throughout.
      responses += ["'%s':'%s'" % (suite.key(), suite.name)]
    self.response.out.write('{%s}' % ','.join(responses))


class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      nickname = user.nickname() + '&nbsp;|&nbsp'
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Sign out'
    else:
      nickname = ''
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Sign in'
    template_values = {
      'nickname': nickname,
      'url': url,
      'url_linktext': url_linktext
    }
    path = os.path.join(os.path.dirname(__file__), 'benchrunner.html')
    self.response.out.write(template.render(path, template_values))


def main():
  application = webapp.WSGIApplication([('/saveruns', SaveRuns),
                                        ('/savebench', SaveBench),
                                        ('/savesuite', SaveSuite),
                                        ('/getsuite', GetSuite),
                                        ('/listsuites', ListSuites),
                                        ('/', MainPage)],
                                       #debug=True
                                       )
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
